package cn.hnu.qq.client.controller;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Map;
import java.util.Set;

import cn.hnu.qq.entity.ChartContent;
import cn.hnu.qq.entity.Crowd;
import cn.hnu.qq.entity.User;
import cn.hnu.qq.entity.message.CrowdChartMessage;
import cn.hnu.qq.entity.message.CrowdInfoMessage;
import cn.hnu.qq.entity.message.QueryCrowdInfoMessage;
import cn.hnu.qq.global.MessageType;
/**
 * 针对群组聊天的控制器
 * @author jared
 *
 */
public class CrowdController extends CenterController {

	private static CrowdController instance = null;
	
	private CrowdController(){};
	
	public static synchronized CrowdController getInstance(){
		if(instance == null){
			instance = new CrowdController();
		}
		return instance;
	}
	
	public void queryCrowdIpInfo(Crowd crowd) {
		log.debug("查询群组ip 端口 信息 : "+crowd.getId() + " : "+ crowd.getCrowdName());
		QueryCrowdInfoMessage qcim = new QueryCrowdInfoMessage();
		qcim.setCrowdName(crowd.getCrowdName());
		try {
			getOutput().writeObject(qcim);
			getOutput().flush();
		} catch (IOException e) {
			log.error("查询群组信息失败");
			e.printStackTrace();
		}
		
	}

	public void sendMessage(Crowd crowd, String info) throws Exception {
		Set<User> users = crowd.getUsers();
		for(User u:users){
			if(u.getIp()!= null && u.getUserClientPort() != null && !u.getAcount().equals(getCurUser().getAcount())){
				CrowdChartMessage ccm = new CrowdChartMessage();
				ccm.setAccount(getCurUser().getAcount());
				ccm.setMes(info);
				ccm.setCrowdName(crowd.getCrowdName());
				byte[] data = ObjectToArray(ccm);
				DatagramPacket dp = new DatagramPacket(data, data.length, InetAddress.getByName(u.getIp()), u.getUserClientPort());
				getdSocket().send(dp);
				log.debug(getCurUser().getAcount()+"发送群聊消息给："+u.getAcount());
			}
		}
	}

	public void sendUploadMessage(Crowd crowd, String text) {
		ChartContent cc = new ChartContent();
		cc.setMessageType(MessageType.UPLOAD_CHART_CONTENT);
		cc.setOwner(getCurUser());
		cc.setCrowd(crowd);
		cc.setContent(text);
		cc.setTime(new Date());
		try {
			getOutput().writeObject(cc);
			getOutput().flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
